package com.lwc.cfdns.config;

import com.lwc.cfdns.interceptor.AdminTokenInterceptor;
import com.lwc.cfdns.interceptor.ApiTokenInterceptor;
import com.lwc.cfdns.constants.ConstantsUrl;
import com.lwc.cfdns.utils.SpringContextUtils;
import org.springframework.boot.autoconfigure.web.servlet.MultipartProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

/**
 * 拦截器
 *
 * @author luwc
 * @version 1.0.0
 * @time 2023/4/22 09:25:59
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    private ApiTokenInterceptor apiTokenInterceptor;

//    @Resource
//    private AdminTokenInterceptor adminTokenInterceptor;

    /**
     * 注册拦截器
     *
     * @param registry
     * @return void
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/4/22 09:29:15
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // API
        registry.addInterceptor(apiTokenInterceptor)
                .addPathPatterns(ConstantsUrl.API + "/**") // 需要拦截的
                .excludePathPatterns(ConstantsUrl.API + "/login"); // 不需要拦截的

        // ADMIN
        // 后台的不用这个拦截器了，直接用过滤器实现security的授权认证
//        registry.addInterceptor(adminTokenInterceptor)
//                .addPathPatterns(ConstantsUrl.ADMIN) // 需要拦截的
//                .excludePathPatterns(ConstantsUrl.ADMIN + "/login/in"); // 不需要拦截的
    }

    /**
     * 跨域配置
     *
     * @param registry
     * @return void
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/5/16 10:19:00
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 置允诈跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许cookie
                .allowCredentials(false)
                // 设置允许的请求方式
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                // 设置允许的header属性
                .allowedHeaders("*")
                // 跨域允许时间
                .maxAge(3600);
    }

    /**
     * 静态资源映射
     *
     * @param registry
     * @return void
     * @throws
     * @version 1.0.0
     * @author luwc
     * @time 2023/6/2 13:10:37
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(AttachmentLocalConfig.getUploadPath() + "**")
                .addResourceLocations("file:" + SpringContextUtils.getBean(MultipartProperties.class).getLocation());
    }
}
